package com.ray.business.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.base.service.BaseCustomerService;
import com.ray.base.service.compose.GoodsService;
import com.ray.base.table.entity.BaseCustomer;
import com.ray.base.table.vo.material.model.MaterialModelVO;
import com.ray.business.builder.PurchaseBackBuilder;
import com.ray.business.builder.PurchaseBackRecordBuilder;
import com.ray.business.builder.PurchaseGoodsBuilder;
import com.ray.business.check.PurchaseBackCheck;
import com.ray.business.check.PurchaseCheck;
import com.ray.business.enums.SaleStatusEnum;
import com.ray.business.service.ProdPurchaseBackRecordService;
import com.ray.business.service.ProdPurchaseBackService;
import com.ray.business.service.ProdPurchaseRecordService;
import com.ray.business.service.ProdPurchaseService;
import com.ray.business.table.dto.PurchaseBackQueryDTO;
import com.ray.business.table.entity.ProdPurchase;
import com.ray.business.table.entity.ProdPurchaseBack;
import com.ray.business.table.entity.ProdPurchaseBackRecord;
import com.ray.business.table.entity.ProdPurchaseRecord;
import com.ray.business.table.params.purchase.back.PurchaseBackCreateParams;
import com.ray.business.table.params.purchase.back.PurchaseBackEditParams;
import com.ray.business.table.params.purchase.back.PurchaseBackQueryParams;
import com.ray.business.table.vo.PurchaseBackVO;
import com.ray.business.table.vo.PurchaseGoodsVO;
import com.ray.common.SysMsgCodeConstant;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.wms.builder.GoodsBuilder;
import com.ray.wms.service.WmsWarehouseService;
import com.ray.wms.service.compose.InService;
import com.ray.wms.service.compose.OutService;
import com.ray.wms.table.dto.GoodsDTO;
import com.ray.wms.table.dto.OrderCreateDTO;
import com.ray.wms.table.entity.WmsWarehouse;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description:
 * @Class: PurchaseBackBackApi
 * @Package com.ray.business.api
 * @date 2020/6/8 13:39
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
@Slf4j
public class PurchaseBackApi {

    @Autowired
    private ProdPurchaseBackService prodPurchaseBackService;
    @Autowired
    private ProdPurchaseBackRecordService prodPurchaseBackRecordService;
    @Autowired
    private BaseCustomerService baseCustomerService;
    @Autowired
    private WmsWarehouseService wmsWarehouseService;
    @Autowired
    private OutService outService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ProdPurchaseService prodPurchaseService;
    @Autowired
    private ProdPurchaseRecordService prodPurchaseRecordService;



    /**
     * 查询采购订单列表信息 分页  非删除的
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<PurchaseBackVO>> pagePurchaseBacks(CommonPage<PurchaseBackQueryParams, Page<PurchaseBackVO>> queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        Map<String, WmsWarehouse> wmsWarehouseMap = new HashMap<>();
        Map<String, BaseCustomer> baseCustomerMap = new HashMap<>();
        CommonPageBuilder<PurchaseBackQueryDTO, ProdPurchaseBack> commonPageBuilder = new CommonPageBuilder<>(PurchaseBackQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<ProdPurchaseBack> page = prodPurchaseBackService.page(commonPageBuilder.bulid(), loginUser);
        List<ProdPurchaseBack> orders = page.getRecords();
        //结果对象
        IPage<PurchaseBackVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if (ObjectUtil.isNotNull(orders)) {
            pageList.setRecords(orders.stream().map(sysPurchaseBack -> {
                PurchaseBackVO orderVO = new PurchaseBackVO();
                BeanUtil.copyProperties(sysPurchaseBack, orderVO);
                //查询客信息
                BaseCustomer baseCustomer = baseCustomerMap.get(sysPurchaseBack.getCustomerCode());
                if (ObjectUtil.isEmpty(baseCustomer)) {
                    baseCustomer = baseCustomerService.queryCustomerByCustomerCode(sysPurchaseBack.getCustomerCode(), loginUser);
                    baseCustomerMap.put(sysPurchaseBack.getCustomerCode(), baseCustomer);
                }
                orderVO.setCustomerName(baseCustomer.getCustomerName());
                //查询仓库信息
                WmsWarehouse wmsWarehouse = wmsWarehouseMap.get(sysPurchaseBack.getWarehouseCode());
                if (ObjectUtil.isEmpty(wmsWarehouse)) {
                    wmsWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(sysPurchaseBack.getWarehouseCode(), loginUser);
                    wmsWarehouseMap.put(wmsWarehouse.getWarehouseCode(), wmsWarehouse);
                }
                orderVO.setWarehouseName(wmsWarehouse.getWarehouseName());
                return orderVO;
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }


    /**
     * 创建订单
     *
     * @param createParams 创建对象
     * @return Result
     */
    @Transactional
    public Result<String> createOrder(PurchaseBackCreateParams createParams) {
        ValidateUtil.validate(createParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //查询采购订单数据
        ProdPurchase prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(createParams.getOrderNo(), loginUser);
        new PurchaseCheck(prodPurchase).checkNull("采购退货单不存在").checkFinish(SysMsgCodeConstant.Error.ERR10000021);
        PurchaseBackBuilder orderBuilder = new PurchaseBackBuilder();
        orderBuilder.append(createParams).append(prodPurchase).appendStatus(SaleStatusEnum.UN_CHECK.getValue()).appendCreate(loginUser);
        //总数
        final List<BigDecimal> quantity = new ArrayList<>();
        //金额统计
        final List<BigDecimal> total = new ArrayList<>();
        //保存商品信息
        List<ProdPurchaseBackRecord> records = createParams.getGoods().stream().map(purchaseGoodsParams -> {
            //查询商品是否存在
            ProdPurchaseRecord prodPurchaseRecord = prodPurchaseRecordService.queryRecord(purchaseGoodsParams,prodPurchase.getOrderNo(),loginUser);
            if(ObjectUtil.isNull(prodPurchaseRecord)){
                log.info("商品{}不在订单中",JSON.toJSONString(purchaseGoodsParams));
                throw BusinessExceptionFactory.newException(SysMsgCodeConstant.Error.ERR10000022);
            }
            //采购退回订单数量
            quantity.add(purchaseGoodsParams.getQuantity());
            //计算单个商品总价
            total.add(purchaseGoodsParams.getQuantity().multiply(NumberUtil.null2Zero(prodPurchaseRecord.getPrice())));
            //已退回数量
            BigDecimal backQuantity = prodPurchaseBackRecordService.queryBackQuantity(createParams.getOrderNo(),null,purchaseGoodsParams,loginUser);
            //判断退回商品数量
            if(prodPurchaseRecord.getQuantity().subtract(backQuantity).compareTo(purchaseGoodsParams.getQuantity()) <0){
                log.info("商品{}可退数量:{},实际数量:{}",JSON.toJSONString(purchaseGoodsParams),
                        prodPurchaseRecord.getQuantity().subtract(backQuantity),purchaseGoodsParams.getQuantity());
                throw BusinessExceptionFactory.newException(SysMsgCodeConstant.Error.ERR10000024);
            }
            return new PurchaseBackRecordBuilder().append(purchaseGoodsParams).appendOrderNo(prodPurchase.getOrderNo())
                    .appendRecordCode(prodPurchaseRecord.getCode())
                    .appendPrice(prodPurchaseRecord.getPrice()).appendCode(orderBuilder.getCode()).appendCreate(loginUser).bulid();
        }).collect(Collectors.toList());
        //保存总数
        orderBuilder.append(quantity.stream().reduce(BigDecimal::add).get());
        //保存总价
        orderBuilder.appendTotal(total.stream().reduce(BigDecimal::add).get());
        //保存订单信息
        if (!prodPurchaseBackService.save(orderBuilder.bulid())) {
            log.info("保存订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        //保存数据
        prodPurchaseBackRecordService.saveBatch(records);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }

    /**
     * 编辑订单
     *
     * @param editParams 编辑对象
     * @return Result
     */
    @Transactional
    public Result<String> editOrder(PurchaseBackEditParams editParams) {
        ValidateUtil.validate(editParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchaseBack prodPurchaseBack = prodPurchaseBackService.queryPurchaseBackByPurchaseBackCode(editParams.getBackCode(), loginUser);
        new PurchaseBackCheck(prodPurchaseBack).checkNull("采购退货单不存在").checkCanEdit(SysMsgCodeConstant.Error.ERR10000018);
        ProdPurchase prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(prodPurchaseBack.getOrderNo(), loginUser);
        new PurchaseCheck(prodPurchase).checkNull("采购退货单不存在").checkFinish(SysMsgCodeConstant.Error.ERR10000021);
        PurchaseBackBuilder orderBuilder = new PurchaseBackBuilder();
        orderBuilder.append(editParams).appendEdit(loginUser);
        //总数
        final List<BigDecimal> quantity = new ArrayList<>();
        //金额统计
        final List<BigDecimal> total = new ArrayList<>();
        //删除数据
        prodPurchaseBackRecordService.deleteOrderGoods(editParams.getBackCode(), loginUser);
        //保存商品信息
        List<ProdPurchaseBackRecord> records = editParams.getGoods().stream().map(purchaseGoodsParams -> {
            //查询商品是否存在
            ProdPurchaseRecord prodPurchaseRecord = prodPurchaseRecordService.queryRecord(purchaseGoodsParams,prodPurchase.getOrderNo(),loginUser);
            if(ObjectUtil.isNull(prodPurchaseRecord)){
                log.info("商品{}不在订单中",JSON.toJSONString(purchaseGoodsParams));
                throw BusinessExceptionFactory.newException(SysMsgCodeConstant.Error.ERR10000022);
            }
            //采购退回订单数量
            quantity.add(purchaseGoodsParams.getQuantity());
            //计算单个商品总价
            total.add(purchaseGoodsParams.getQuantity().multiply(NumberUtil.null2Zero(prodPurchaseRecord.getPrice())));
            //已退回数量
            BigDecimal backQuantity = prodPurchaseBackRecordService.queryBackQuantity(editParams.getOrderNo(),prodPurchaseBack.getBackCode()
                    ,purchaseGoodsParams,loginUser);
            //判断退回商品数量
            if(prodPurchaseRecord.getQuantity().subtract(backQuantity).compareTo(purchaseGoodsParams.getQuantity()) <0){
                log.info("商品{}可退数量:{},实际数量:{}",JSON.toJSONString(purchaseGoodsParams),
                        prodPurchaseRecord.getQuantity().subtract(backQuantity),purchaseGoodsParams.getQuantity());
                throw BusinessExceptionFactory.newException(SysMsgCodeConstant.Error.ERR10000024);
            }
            return new PurchaseBackRecordBuilder().append(purchaseGoodsParams).appendOrderNo(prodPurchase.getOrderNo())
                    .appendRecordCode(prodPurchaseRecord.getCode())
                    .appendPrice(prodPurchaseRecord.getPrice()).appendCode(orderBuilder.getCode()).appendCreate(loginUser).bulid();
        }).collect(Collectors.toList());
        //保存总数
        orderBuilder.append(quantity.stream().reduce(BigDecimal::add).get());
        //保存总价
        orderBuilder.appendTotal(total.stream().reduce(BigDecimal::add).get());
        //编辑订单信息
        if (!prodPurchaseBackService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("编辑订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        //保存数据
        prodPurchaseBackRecordService.saveBatch(records);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }


    /**
     * 审核通过
     *
     * @param backCode
     * @return
     */
    @Transactional
    public Result<String> passOrder(String backCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchaseBack prodPurchaseBack = prodPurchaseBackService.queryPurchaseBackByPurchaseBackCode(backCode, loginUser);
        new PurchaseBackCheck(prodPurchaseBack).checkNull("采购退货单不存在").checkCanCheck(SysMsgCodeConstant.Error.ERR10000020);
        ProdPurchase prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(prodPurchaseBack.getOrderNo(), loginUser);
        new PurchaseCheck(prodPurchase).checkNull(SysMsgCodeConstant.Error.ERR10000002).checkFinish(SysMsgCodeConstant.Error.ERR10000020);
        PurchaseBackBuilder orderBuilder = new PurchaseBackBuilder();
        orderBuilder.appendCode(backCode).appendEdit(loginUser).appendStatus(SaleStatusEnum.UN_OUT.getValue());
        //编辑订单信息
        if (!prodPurchaseBackService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("审核订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        OrderCreateDTO orderCreateDTO = new OrderCreateDTO();
        orderCreateDTO.setBusinessOrderNo(prodPurchase.getBusinessOrderNo());
        orderCreateDTO.setBusinessCode(backCode);
        orderCreateDTO.setWarehouseCode(prodPurchaseBack.getWarehouseCode());
        //查询订单商品
        List<ProdPurchaseBackRecord> records = prodPurchaseBackRecordService.list(backCode, loginUser);
        List<GoodsDTO> goodsDTOS = records.stream().map(prodPurchaseBackRecord -> {
            return new GoodsBuilder().append(prodPurchaseBackRecord).appendOrderNo(prodPurchase.getBusinessOrderNo()).bulid();
        }).collect(Collectors.toList());
        orderCreateDTO.setGoodsDTOS(goodsDTOS);
        //创建订单
        outService.createOrderOut(orderCreateDTO, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, backCode);
    }

    /**
     * 删除
     *
     * @param backCode
     * @return
     */
    @Transactional
    public Result<String> deleteOrder(String backCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchaseBack prodPurchaseBack = prodPurchaseBackService.queryPurchaseBackByPurchaseBackCode(backCode, loginUser);
        new PurchaseBackCheck(prodPurchaseBack).checkNull("采购退货单不存在").checkCanCheck("采购退货单不能删除");
        PurchaseBackBuilder orderBuilder = new PurchaseBackBuilder();
        orderBuilder.appendCode(backCode).appendEdit(loginUser).delete();
        //编辑订单信息
        if (!prodPurchaseBackService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("编辑订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        //删除数据
        prodPurchaseBackRecordService.deleteOrderGoods(backCode, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, backCode);
    }


    /**
     * 取消
     *
     * @param backCode
     * @return
     */
    @Transactional
    public Result<String> cancelOrder(String backCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchaseBack prodPurchaseBack = prodPurchaseBackService.queryPurchaseBackByPurchaseBackCode(backCode, loginUser);
        new PurchaseBackCheck(prodPurchaseBack).checkNull("采购退货单不存在").checkCanCancel("采购退货不能取消");
        PurchaseBackBuilder orderBuilder = new PurchaseBackBuilder();
        orderBuilder.appendCode(backCode).appendStatus(SaleStatusEnum.CANCEL.getValue()).appendEdit(loginUser);
        //编辑订单信息
        if (!prodPurchaseBackService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("取消订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("取消订单接口异常");
        }
        //删除数据
        prodPurchaseBackRecordService.deleteOrderGoods(backCode, loginUser);
        //作废出库订单
        outService.invalidOrderBusinessCode(backCode, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, backCode);
    }


    /**
     * 订单详情
     *
     * @param orderNo
     * @return
     */
    public Result<PurchaseBackVO> viewOrder(String orderNo) {
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchaseBack prodPurchaseBack = prodPurchaseBackService.queryPurchaseBackByPurchaseBackCode(orderNo, loginUser);
        new PurchaseBackCheck(prodPurchaseBack).checkNull("采购退货单不存在");
        PurchaseBackVO purchaseVO = new PurchaseBackVO();
        BeanUtil.copyProperties(prodPurchaseBack, purchaseVO);
        //查询客信息
        BaseCustomer baseCustomer = baseCustomerService.queryCustomerByCustomerCode(prodPurchaseBack.getCustomerCode(), loginUser);
        if (ObjectUtil.isNotNull(baseCustomer)) {
            purchaseVO.setCustomerName(baseCustomer.getCustomerName());
        }
        //查询仓库信息
        WmsWarehouse wmsWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(prodPurchaseBack.getWarehouseCode(), loginUser);
        if (ObjectUtil.isNotNull(wmsWarehouse)) {
            purchaseVO.setWarehouseName(wmsWarehouse.getWarehouseName());
        }
        //查询
        List<ProdPurchaseBackRecord> prodPurchaseBackRecords = prodPurchaseBackRecordService.list(orderNo, loginUser);
        Map<String, MaterialModelVO> modelMap = new HashMap<>();
        List<PurchaseGoodsVO> purchaseGoodsVOS = prodPurchaseBackRecords.stream().map(prodPurchaseBackRecord -> {
            MaterialModelVO materialModelVO = modelMap.get(prodPurchaseBackRecord.getGoodsCode());
            if (ObjectUtil.isNull(materialModelVO)) {
                materialModelVO = goodsService.queryGoodsByCode(prodPurchaseBackRecord.getGoodsCode(), loginUser);
                modelMap.put(prodPurchaseBackRecord.getGoodsCode(),materialModelVO);
            }
            return new PurchaseGoodsBuilder().append(prodPurchaseBackRecord).append(materialModelVO).bulid();
        }).collect(Collectors.toList());
        purchaseVO.setGoods(purchaseGoodsVOS);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, purchaseVO);
    }
}
